import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Spin } from 'antd';
import moment from 'moment';
import { columns } from './components/Container/helper';
import { useTRState } from '#/utils/trHooks.jsx';
import { PageLoading } from '@/components';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import { useExcel } from '@/hooks';
import Header from './components/Header';
import styles from './index.less';
import Container from './components/Container';
import { queryMarketList, GreenCertificateData } from './services';
import { getTreeByCodes } from '@/utils';

const GreenCertificateOverview = ({ menuCode, buttonPermissions }) => {
  const [state, setState] = useTRState({
    error: '',
    firstLoading: true,
    loading: false,
    power: [], // 数据权限
    dataSource: [],
    exportTable: [],
    params: {},
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setState({ firstLoading: true });
    let error = '';
    let power = [];
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['station'], res.json).treeOptions;
    } else {
      error = res?.message;
    }
    setState({
      error,
      power,
      firstLoading: false,
    });
  };
  const getDataSource = async (params = state.params) => {
    setState({ loading: true });
    const res = await GreenCertificateData(params);
    if (res.statusCode === HttpCode.SUCCESS) {
      setState({ dataSource: res.data, params, loading: false });
    }
  };
  const _onExport = () => {
    // if (!state.canExport) return Message.info('请联系管理员获取相关权限');
    // 导出
    let headerColumns = columns.map((item) => {
      let obj = { ...item, name: item.title };
      if (obj.hasOwnProperty('render')) {
        delete obj.render;
      }
      return obj;
    });

    useExcel({
      filename: `${moment().format('YYYY.MM.DD HH：mm：ss')}'绿证概览`,
      columns: headerColumns,
      data: state.dataSource,
    });
  };
  const { firstLoading, power, loading, params, error, dataSource } = state;
  if (firstLoading) return <PageLoading />;
  if (error) return <TRDefault type="error" message={state.error} />;
  if (!power.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.body}>
      <Header power={power} loading={loading} getDataSource={getDataSource} onExport={_onExport} />
      <div className={styles.box}>
        <div className={styles.content}>
          {loading ? (
            <PageLoading />
          ) : (
            <Container dataSource={dataSource} getDataSource={getDataSource} params={params} />
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(GreenCertificateOverview);
